//
//  DiscoverNewWIFIViewController.m
//  Router
//
//  Created by teki on 15/11/12.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "DiscoverNewWIFIController.h"
#import "BindWiFITableViewCell.h"
#import "DiscoverHelper.h"
#import "BindDeviceViewController.h"

@interface DiscoverNewWIFIController ()
@property (nonatomic, strong) DiscoverHelper *discoverHelper;
@property (nonatomic, strong) NSDictionary *responseDict;

@end

@implementation DiscoverNewWIFIController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"发现小叶WIFI";
    
    self.discoverHelper = [[DiscoverHelper alloc] init];

    self.tableView.tableHeaderView = [self getTableViewHeaderView];
    self.tableView.tableFooterView = [UIView new];

    [self.tableView registerNib:[UINib nibWithNibName:@"BindWiFITableViewCell" bundle:nil] forCellReuseIdentifier:@"BindWiFITableViewCell"];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findNewWIFI) name:UIApplicationDidBecomeActiveNotification object:nil];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self findNewWIFI];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [super viewWillDisappear:animated];
    
}


#pragma mark -
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.contentList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BindWiFITableViewCell *cell = (BindWiFITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"BindWiFITableViewCell" forIndexPath:indexPath];
    
    
    NSDictionary *dict = self.contentList[indexPath.row];
    BOOL isBind = [dict[@"isBind"] boolValue];
    if (!isBind)
    {
        cell.bindButton.hidden = NO;
        NSString *ssid = self.responseDict[@"ssid"];
        if (ssid)
        {
            NSString *string = [NSString stringWithFormat:@"未绑定的小叶WIFI%@",ssid];
            NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc] initWithString:string];
            NSRange range = [string rangeOfString:ssid];
            [mutableString addAttributes:@{NSForegroundColorAttributeName:NavgationBarBackgroundColor} range:NSMakeRange(0, range.location)];
            [mutableString addAttributes:@{NSForegroundColorAttributeName:SeparatorLineColor} range:range];
            cell.unBindDeviceLabel.attributedText = mutableString;
        }
        else
        {
            cell.unBindDeviceLabel.text = @"未绑定的小叶WIFI";
        }
    }
    else{
        cell.unBindDeviceLabel.text = @"您的小叶WIFI被别人绑定了!";
        cell.bindButton.hidden = YES;
    }

    WEAKSELF
    [cell setBindButtonClick:^{
        STRONGSELF
        [strongSelf gotoBindViewController];
    }];
    
    return cell;
}

- (void)gotoBindViewController
{
    BindDeviceViewController *viewcontroller = [[BindDeviceViewController alloc] init];
    viewcontroller.responseDict = self.responseDict;
    [self.navigationController pushViewController:viewcontroller animated:YES];
}



#pragma mark -
#pragma mark   Requests
- (void)findNewWIFI
{
    __weak __typeof(self)weakSelf = self;
    [self.discoverHelper discoverWIFISuccess:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"responseObject:%@",responseObject);
        if (responseObject)
        {
            strongSelf.responseDict = responseObject;
            NSString *info = responseObject[@"info"];
            if ([info isEqualToString:@"InterNetNotConnected"])
            {
//                [self showNOWIFIDeviceView];
            }
            else if ([info isEqualToString:@"InterNetConnected"])
            {
                NSString *deviceID = responseObject[@"deviceID"];
                [strongSelf checkDeviceInBindWithDeviceID:deviceID];
            }
        }
        else
        {
//            [self showNOWIFIDeviceView];
        }
        
    } failure:^(NSError *error) {
//        [self showNOWIFIDeviceView];
    }];
}



- (void)checkDeviceInBindWithDeviceID:(NSString *)deviceID
{
    if (deviceID) {
        [self.discoverHelper getWIFIBindDeviceWithDeviceID:deviceID success:^(BOOL succ, id responseObject, NSString *msg) {
            if (responseObject) {
                BOOL bindOrNot = [responseObject[@"isBind"] boolValue];
                if (!bindOrNot)
                {
                    self.contentList = [NSMutableArray arrayWithObject:responseObject];
                    [self.tableView reloadData];
                }
            }
        } failure:^(NSError *error) {
            NSString *failedReason = [error localizedDescription];
            [self stopActivityWithActivity:self.activity title:failedReason];
        }];
    }
    
}


#pragma mark -
#pragma mark   setters and getters
- (UIView *)getTableViewHeaderView
{
    UIImage *bgImage = [UIImage imageNamed:@"animation1.gif"];
    CGFloat bgScale = bgImage.size.width/bgImage.size.height;   //宽高比
    CGFloat h = ScreenWidth / bgScale;                          //图片等比例高
    //    CGFloat scale = (h/bgImage.size.height);                    //压缩\拉伸比例
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, h)];
    
    // 读取gif图片数据
    NSData *gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"animation1" ofType:@"gif"]];
    // view生成
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, h)];
    webView.userInteractionEnabled = NO;//用户不可交互
    webView.scalesPageToFit  = YES;
    [webView loadData:gif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
    [headView addSubview:webView];

    
    return headView;
}


@end
